<template>
  <div class="predict-container">
    <div class="model-select-section">
      <h3>选择训练好的模型</h3>
      <el-select v-model="selectedModel" placeholder="请选择模型" @change="handleModelSelect">
        <el-option v-for="model in trainedModels" :key="model.id" :label="model.name" :value="model.id" />
      </el-select>
    </div>

    <div class="data-input-section" v-if="selectedModel">
      <h3>输入预测数据</h3>
      <el-upload
        class="upload-demo"
        action="http://localhost:3000/api/predict/upload"
        :limit="1"
        :on-exceed="handleExceed"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :on-error="handleError"
        accept=".csv">
        <template #trigger>
          <el-button type="primary">选择数据文件</el-button>
        </template>
        <template #tip>
          <div class="el-upload__tip">
            请上传CSV格式的数据文件
          </div>
        </template>
      </el-upload>
    </div>

    <div class="prediction-section" v-if="isPredicting">
      <h3>预测进度</h3>
      <el-progress :percentage="predictionProgress" />
      <div class="prediction-logs">
        <pre>{{ predictionLogs }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const selectedModel = ref('')
const trainedModels = ref([])
const isPredicting = ref(false)
const predictionProgress = ref(0)
const predictionLogs = ref('')

// 获取训练好的模型列表
const fetchTrainedModels = async () => {
  try {
    const response = await fetch('http://localhost:3000/api/models')
    const data = await response.json()
    if (data.success) {
      trainedModels.value = data.models
    }
  } catch (error) {
    ElMessage.error('获取模型列表失败')
  }
}

const handleModelSelect = (modelId) => {
  predictionProgress.value = 0
  predictionLogs.value = ''
}

const handleExceed = (files) => {
  ElMessage.warning('只能上传一个文件')
}

const beforeUpload = (file) => {
  const isCSV = file.type === 'text/csv' || file.name.toLowerCase().endsWith('.csv')
  if (!isCSV) {
    ElMessage.error('请上传CSV文件！')
    return false
  }
  return true
}

const handleSuccess = async (response) => {
  if (response.success) {
    ElMessage.success('文件上传成功，开始预测')
    startPrediction(response.fileId)
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleError = (error) => {
  ElMessage.error('文件上传失败')
}

const startPrediction = async (fileId) => {
  try {
    isPredicting.value = true
    predictionProgress.value = 0
    predictionLogs.value = ''

    const response = await fetch('http://localhost:3000/api/predict', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        modelId: selectedModel.value,
        fileId: fileId
      })
    })

    const result = await response.json()
    if (result.success) {
      ElMessage.success('预测完成')
      // 触发预测展示更新
      // TODO: 实现预测结果的展示逻辑
    } else {
      throw new Error(result.message)
    }
  } catch (error) {
    ElMessage.error('预测失败：' + error.message)
  } finally {
    isPredicting.value = false
  }
}

onMounted(() => {
  fetchTrainedModels()
})
</script>

<style lang="scss" scoped>
.predict-container {
  padding: 20px;
}

.model-select-section,
.data-input-section,
.prediction-section {
  margin-bottom: 30px;
}

.prediction-logs {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;

  pre {
    margin: 0;
    white-space: pre-wrap;
    word-wrap: break-word;
  }
}
</style> 